package com.vois.jack.btmgr.util;

import android.os.Environment;
import android.util.Log;

import com.vois.jack.btmgr.BuildConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Logger {
	/**
	 * log tag
	 */
	private String tagName = "JC_BT:";// tag name
	private String className;
	private int logLevel = Log.VERBOSE;
	private String fileLogRootPath;
	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
			'E', 'F' };

	private void init(int logLevel) {
		try {
			fileLogRootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "weila" + File.separator + "Logs";
		}catch (Exception e) {
			e.printStackTrace();
			fileLogRootPath = null;
		}

		this.logLevel = logLevel;
	}

	private Logger() {
		if (!BuildConfig.BUILD_TYPE.equals("debug")) {
			init(Log.INFO);
		}
	}

	private Logger(int logLevel) {
		init(logLevel);
	}

	public static Logger getLogger(Class<?> key, int logLevel) {
		return new Logger(logLevel);
	}

	public static Logger getLogger(Class<?> key) {
		return new Logger();
	}

	private String getFunctionName() {
		StackTraceElement[] sts = Thread.currentThread().getStackTrace();

		if (sts == null) {
			return null;
		}

		for (StackTraceElement st : sts) {
			if (st.isNativeMethod()) {
				continue;
			}

			if (st.getClassName().equals(Thread.class.getName())) {
				continue;
			}

			if (st.getClassName().equals(this.getClass().getName())) {
				continue;
			}

			return "[" + st.getFileName() + ":" + st.getLineNumber() + "]";
		}

		return null;
	}

	private String createMessage(String msg) {
		String functionName = getFunctionName();
		long threadId = Thread.currentThread().getId();
		String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
		String message = (functionName == null ? msg : (functionName + " - "
				+ String.valueOf(threadId) + " - " + msg));
        String finalRes = currentTime + " - " + message;
		return finalRes;
	}

	/**
	 * log.i
	 */
	public void i(String format, Object... args) {
		if (logLevel <= Log.INFO) {
			String message = createMessage(getInputString(format, args));
			Log.i(tagName, message);
		}
	}

	/**
	 * log.v
	 */
	public void v(String format, Object... args) {
		if (logLevel <= Log.VERBOSE) {
			String message = createMessage(getInputString(format, args));
			Log.v(tagName, message);
		}
	}

	/**
	 * log.d
	 */
	public void d(String format, Object... args) {
		if (logLevel <= Log.DEBUG) {
			String message = createMessage(getInputString(format, args));
			Log.d(tagName, message);
		}
	}

	/**
	 * log.e
	 */
	public void e(String format, Object... args) {
		if (logLevel <= Log.ERROR) {
			String message = createMessage(getInputString(format, args));
			Log.e(tagName, message);
		}
	}

	private String getInputString(String format, Object... args) {
		if (format == null) {
			return "null log format";
		}

		return String.format(format, args);
	}

	/**
	 * log.error
	 */
	public void error(Exception e) {
		if (logLevel <= Log.ERROR) {
			StringBuffer sb = new StringBuffer();
			try {
				String name = getFunctionName();
				if(e == null){
					sb.append("e == null" + "\r\n");
				}else{
					StackTraceElement[] sts = e.getStackTrace();

					if (name != null) {
						sb.append(name + " - " + e + "\r\n");
					} else {
						sb.append(e + "\r\n");
					}
					if (sts != null && sts.length > 0) {
						for (StackTraceElement st : sts) {
							if (st != null) {
								sb.append("[ " + st.getFileName() + ":"
										+ st.getLineNumber() + " ]\r\n");
							}
						}
					}
				}
				Log.e(tagName, sb.toString());
			}catch (Exception ex){

			}
		}
	}
	/**
	 * log.d
	 */
	public void w(String format, Object... args) {
		if (logLevel <= Log.WARN) {
			String message = createMessage(getInputString(format, args));
			Log.w(tagName, message);
		}
	}

	public void f(String format, Object... args){
        if (logLevel <= Log.WARN) {
			String message = createMessage(getInputString(format, args));
			Log.w(tagName, message);
			writeToFile(message);
        }
    }

    private void writeToFile(String message){
		if (fileLogRootPath != null) {
			File file = new File(fileLogRootPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);//日期格式;
			String fileName = fileLogRootPath + "/log_" + dateFormat.format(new Date()) + ".log";
			FileOutputStream fos = null;
			BufferedWriter bw = null;
			try {
				fos = new FileOutputStream(fileName, true);//这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
				bw = new BufferedWriter(new OutputStreamWriter(fos));
				bw.write(message + "\n");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (bw != null) {
						bw.close();//关闭缓冲流
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    }

	/**
	 * set log level
	 */
	public void setLevel(int l) {
		logLevel = l;
	}

	public void dumpArray(byte[] data, int dataSize) {
		char[] out = new char[dataSize * 3];
		try {
			for (int i = 0, j = 0; i < dataSize; i++) {
				out[j++] = DIGITS_UPPER[(0xF0 & data[i]) >>> 4];
				out[j++] = DIGITS_UPPER[0x0F & data[i]];
				out[j++] = ',';
			}

			Log.i(tagName, createMessage("-------------[" + dataSize + "]-----------------"));
			Log.i(tagName, createMessage(new String(out)));
			Log.i(tagName, createMessage("------------------------------------------"));
		}catch (Exception e) {
			e.printStackTrace();
			Log.d(tagName, "dumpArray error: " + e.getMessage());
		}
	}

}
